package cn.usts.edu.lesson08;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重复性锁,相比传统的synchronized
 * ReentrantLock更直观,直观上锁解锁
 * */

public class LockDemo implements Runnable{

    private int tickets=10;

    private final ReentrantLock lock = new ReentrantLock(); // 实例化锁

    public static void main(String[] args) {
        LockDemo lockDemo = new LockDemo();
        new Thread(lockDemo).start();
        new Thread(lockDemo).start();
        new Thread(lockDemo).start();
    }



    @Override
    public void run() {

        try {
            lock.lock();// 上锁

            while (true){
                if (tickets>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(tickets--);
                }
                else {
                    break;
                }
            }
        }finally {
            lock.unlock();// 解锁
        }

    }
}

